package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Other;
import com.gy.mapper.OtherMapper;
import com.gy.query.OtherQuery;
import com.gy.result.Result;
import com.gy.service.OtherService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class OtherServiceImpl extends ServiceImpl<OtherMapper, Other> implements OtherService {
    @Autowired
    private UploadController uploadController;
    @Autowired
    private OtherMapper otherMapper;

    @Autowired
    private UserService userService;
    @Override
    public Result<PageVO<Other>> getOther(OtherQuery otherQuery) {
        Long userId = UserHolder.getUser().getUserId();

        Page<Other> page = Page.of(otherQuery.getPageNo(), otherQuery.getPageSize());

        // 排序条件
        if (!otherQuery.getSortBy().isEmpty() || otherQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(otherQuery.getSortBy(), otherQuery.getIsAsc()));
        } else {
            // 为空，默认按照获得时间排序
            page.addOrder(new OrderItem("obtain_time", false));
        }

        // 构建查询条件
        LambdaQueryChainWrapper<Other> queryWrapper = lambdaQuery().select()
                .eq(userId != null, Other::getUserId, userId);

        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (otherQuery.getStartDate() != null && otherQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(otherQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(otherQuery.getEndDate());
                queryWrapper.between(Other::getObtainTime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        //添加个人排名查询参数
        if (otherQuery.getAuthorRank() != null) {
            queryWrapper.eq(Other::getAuthorRank, otherQuery.getAuthorRank());
        }
        // 执行分页查询
        Page<Other> p = queryWrapper.page(page);

        // 封装VO结果
        PageVO<Other> vo = new PageVO<>();
        vo.setTotal(p.getTotal());
        vo.setPages(p.getPages());
        List<Other> records = p.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }
        return Result.success(vo);
    }

    /**
     * 根据id主键删除其他信息
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removeOtherById(Long id) {
        Other other = getById(id);
        if (other == null) {
            return Result.error("其他信息未找到");
        }

        String pdfUrl = other.getPdfPath();

        // 检查 pdfUrl 是否为空
        if (pdfUrl != null && !pdfUrl.isEmpty()) {
            try {
                uploadController.deleteFile(pdfUrl);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfUrl 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除其他信息失败");
        }
        userService.decrementUserOtherCount();
        return Result.success("其他信息删除成功");
    }

    /**
     * 根据id主键查询其他
     * @param id
     * @return
     */
    @Override
    public Other getOtherById(Long id) {
       if (id==null)
       {
           return null;
       }
        return otherMapper.selectOtherById(id);
    }

    @Override
    public Result updateOther(Other other) {
        // 参数验证
        if (other == null) {
            return Result.error("其他信息不能为空");
        }
        if (other.getId() == null) {
            return Result.error("其他信息ID不能为空");
        }

        try {
            int affectedRows = otherMapper.updateOther(other);
            if (affectedRows > 0) {
                return Result.success(other);
            } else {
                return Result.error("未找到对应的信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新其他信息时发生异常", e);
            return Result.error("更新其他信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveOther(Other other) {
        if (other == null) {
            log.warn("传入的其他对象为空");
            return Result.error("其他对象不能为空");
        }
        try {
            // 设置用户 ID
            other.setUserId(UserHolder.getUser().getUserId());

            boolean save = otherMapper.saveOther(other);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserOtherCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存其他对象时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getOtherByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<Other> otherList = otherMapper.selectOtherBatchIds(Arrays.asList(ids));
            return Result.success(otherList);
        }
        return null;
    }


}
